package org.example.functions;




import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.TimeZone;


public class Clock extends JPanel {
    private int hour;
    private int minute;
    private int second;
    private Image clockImage;

    public Clock() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        this.hour = calendar.get(Calendar.HOUR);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);
        try {
            String basepath = "D:\\java-experiment\\java02\\src\\main\\resources\\R-C.jpg";
            basepath = URLDecoder.decode(basepath,"utf-8");
            clockImage = ImageIO.read(new File(basepath));
        } catch (IOException e) {
//            System.exit(0);
            throw new RuntimeException(e);
        }
    }

    public void currentTime() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"));
        this.hour = calendar.get(Calendar.HOUR);
        this.minute = calendar.get(Calendar.MINUTE);
        this.second = calendar.get(Calendar.SECOND);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);


        int xCenter = getWidth() / 2;
        int yCenter = getHeight() / 2;
        int r = Math.max(xCenter, yCenter);

        g2d.drawImage(clockImage, 0, 0, getWidth(), getHeight(), this);

        //圆点
        final int minR = 30;
        g2d.fillOval(xCenter - minR / 2, yCenter - minR / 2, minR, minR);

        BasicStroke stroke = new BasicStroke(8.0f);
        g2d.setStroke(stroke);
        //秒针
        int sLength = (int) (r * 0.5);
        int xSecond = (int) (xCenter + sLength * Math.sin((second * 2 * Math.PI / 60)));
        int ySecond = (int) (yCenter - sLength * Math.cos((second * 2 * Math.PI / 60)));
        g2d.setColor(Color.red);
        g2d.drawLine(xCenter, yCenter, xSecond, ySecond);

        //分针
        int mLength = (int) (r * 0.35);
        int xMinute = (int) (xCenter + mLength * Math.sin((minute * 2 * Math.PI / 60)));
        int yMinute = (int) (yCenter - mLength * Math.cos((minute * 2 * Math.PI / 60)));
        g2d.setColor(Color.blue);
        g2d.drawLine(xCenter, yCenter, xMinute, yMinute);

        //时针
        int hLength = (int) (r * 0.2);
        int xHour = (int) (xCenter + hLength * Math.sin((hour % 12 * (2 * Math.PI / 12))));
        int yHour = (int) (yCenter - hLength * Math.cos((hour % 12 * (2 * Math.PI / 12))));
        g2d.setColor(Color.green);
        g2d.drawLine(xCenter, yCenter, xHour, yHour);

    }
}
